package com.diandi.activity.service.impl;

import com.diandi.activity.bean.BorrowTypes;
import com.diandi.activity.bean.LotteryTicket;
import com.diandi.activity.bean.PublishPlatformType;
import com.diandi.activity.manager.LotteryTicketManager;
import com.diandi.activity.service.LotteryTicketService;
import com.diandi.ddsb.bean.*;
import com.diandi.ddsb.mapper.TicketOldMapper;
import com.diandi.ddsb.vo.Constant;
import com.diandi.ddsb.vo.LotteryTicketInfoVo;
import com.diandi.ddsb.vo.LotteryTicketType;
import com.diandi.utils.NumberUtil;
import com.diandi.utils.YesOrNoType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * Created by a on 2018/3/27.
 */
@RestController
public class CenterLotteryTicketServiceImpl implements LotteryTicketService {
    @Autowired
    private LotteryTicketManager lotteryTicketManager;
    @Autowired
    private TicketOldMapper ticketOldMapper;
    @SuppressWarnings("rawtypes")
    @Override
    public List<LotteryTicket> queryLotteryTickets(@RequestParam Map paramMap) {
        List<LotteryTicket> list = lotteryTicketManager.queryLotteryTickets(paramMap);
        for (LotteryTicket ticket : list) {
            if (ticket.getPublishPlatforms() != null && !ticket.getPublishPlatforms().equals("")) {
                String publishPlatforms = "";
                String[] strs = ticket.getPublishPlatforms().split(",");
                for (String str : strs) {
                    publishPlatforms += PublishPlatformType.getTextByValue(Integer.parseInt(str)).getText() + "|";
                }
                ticket.setPublishPlatforms(publishPlatforms);
            }
            if (StringUtils.isNotBlank(ticket.getBorrowTypes())) {
                String borrowTypes = "";
                String[] strs = ticket.getBorrowTypes().split(",");
                for (String str : strs) {
                    borrowTypes += BorrowTypes.getTextByValue(Integer.parseInt(str)).getText() + "|";
                }
                ticket.setBorrowTypes(borrowTypes);
            }
        }
        return list;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Integer queryLotteryTicketCount(Map paramMap) {
        return lotteryTicketManager.queryLotteryTicketCount(paramMap);
    }

    @SuppressWarnings("rawtypes")
    @Override
//    @Transactional
    public Result insertLotteryTicket(@RequestBody LotteryTicketInfoVo lotteryTicket) {
        Result result = new Result();
        result.setCode(Constant.SUCCESS);
        // 不是现金红包的时候进行的校验
        if (lotteryTicket.getType() != LotteryTicketType.CASH_PACKAGE.getValue()// 现金红包
                && lotteryTicket.getType() != LotteryTicketType.VIRTUAL_CASH_TICKET.getValue()// 虚拟现金红包（可以先发放，但红包金额不到账需要用户主动领取）
                && lotteryTicket.getType() != LotteryTicketType.BACK_RATE_TICKET.getValue()
                && lotteryTicket.getType() != LotteryTicketType.INTEGRAL_TICKET.getValue()) {// 按投资金额返点现金红包
            checkTicket(lotteryTicket, "startTime");
            checkTicket(lotteryTicket, "validDayStartWithNow");
            checkTicket(lotteryTicket, "validDayStartWithStartTime");
            checkTicket(lotteryTicket, "validDayEndWithendTime");
        }
        // 加息券
        if (lotteryTicket.getType() == LotteryTicketType.ADDINTEREST_TICKET.getValue()) {
            checkTicket(lotteryTicket, "addInterestRate");
            checkTicket(lotteryTicket, "addInterestDays");
            checkTicket(lotteryTicket, "publishPlatforms");
            checkTicket(lotteryTicket, "borrowTypes");
            checkTicket(lotteryTicket, "borrowLoanPeriods");
            lotteryTicket.setAddInterestRate(NumberUtil.doubleDivide(lotteryTicket.getAddInterestRate(), 100d));
        }
        // 体验金
        else if (lotteryTicket.getType() == LotteryTicketType.EXPERIENCE_TICKET.getValue()) {
            checkTicket(lotteryTicket, "publishPlatforms");
            checkTicket(lotteryTicket, "tasteType");
            checkTicket(lotteryTicket, "tasteTypeWithamount");
            checkTicket(lotteryTicket, "tasteRateDays");
            if (lotteryTicket.getTasteType() == 1 && lotteryTicket.getMaxTasteAmount() != null) {
                lotteryTicket.setMaxInvestAmount(lotteryTicket.getMaxTasteAmount());
            }
            lotteryTicket.setAddInterestDays(lotteryTicket.getTasteRateDays());
        }
        // 免息券
        else if (lotteryTicket.getType() == LotteryTicketType.FREE_TICKET.getValue()) {
            checkTicket(lotteryTicket, "freeTicketValue");
            checkTicket(lotteryTicket, "borrowTypes");
            checkTicket(lotteryTicket, "repaymentTypes");
        }
        // 现金红包
        else if (lotteryTicket.getType() == LotteryTicketType.CASH_PACKAGE.getValue()) {
            checkTicket(lotteryTicket, "cashPackageType");
            lotteryTicket.setTasteType(lotteryTicket.getCashPackageType());

            if (lotteryTicket.getCashPackageType() == YesOrNoType.NO.getValue()) {
                checkTicket(lotteryTicket, "cashPackageAmount");
                lotteryTicket.setAmount(lotteryTicket.getCashPackageAmount());
            } else {
                checkTicket(lotteryTicket, "investBackRate");
                int tasteType = lotteryTicket.getTasteType();
                if(tasteType == TasteType.INVEST_MULTIPLE.getValue() || tasteType == TasteType.INVEST_DAYS.getValue()
                        || tasteType == TasteType.INVEST_RATIO.getValue()){
                    lotteryTicket.setInvestBackRate(NumberUtil.doubleDivide(lotteryTicket.getInvestBackRate(), 100d));
                }
            }
            // 虚拟现金红包（可以先发放，但奖励金额不会到用户账户，需用户主动领取,然后修改奖券状态）
        } else if (lotteryTicket.getType() == LotteryTicketType.VIRTUAL_CASH_TICKET.getValue()) {
            checkTicket(lotteryTicket, "VCT");
            lotteryTicket.setAmount(lotteryTicket.getCashPackageAmount());
            // 返点金红包：按投资比例返给用户现金红包
        } else if (lotteryTicket.getType() == LotteryTicketType.BACK_RATE_TICKET.getValue()) {
            checkTicket(lotteryTicket, "BRT");
            lotteryTicket.setInvestBackRate(NumberUtil.doubleDivide(lotteryTicket.getInvestBackRate(), 100d));
            if (lotteryTicket.getMaxTasteAmount() != null && lotteryTicket.getMaxTasteAmount() > 0) {
                lotteryTicket.setAmount(lotteryTicket.getMaxTasteAmount());
            }
        }else if (lotteryTicket.getType() == LotteryTicketType.INTEGRAL_TICKET.getValue()) {
            if (null == lotteryTicket.getIntegralType()) {
                throw new RuntimeException("新增奖券失败:请填写积分类型！");
            }

            if (lotteryTicket.getIntegralType() == IntegralType.FIXED_INTEGRAL.getValue()) {
                if (lotteryTicket.getIntegralPoints() == null || lotteryTicket.getIntegralPoints() == 0) {
                    throw new RuntimeException("新增奖券失败:请填写积分金额！");
                }
                lotteryTicket.setAmount(lotteryTicket.getIntegralPoints());
            }
        }
        // 通用版
        else {
            checkTicket(lotteryTicket, "amount");
            checkTicket(lotteryTicket, "investMiniAmount");
            checkTicket(lotteryTicket, "publishPlatforms");
            checkTicket(lotteryTicket, "borrowTypes");
            checkTicket(lotteryTicket, "borrowLoanPeriods");
        }
        checkTicket(lotteryTicket, "title");
        //先插入老系统
        ticketOldMapper.insertLotteryTicket(lotteryTicket);
        lotteryTicket.setOldTicketId(lotteryTicket.getId());
        if (lotteryTicketManager.insertLotteryTicket(lotteryTicket) == 1) {
            result.setCode(Constant.SUCCESS);
            result.setMsg("新增奖券成功！");
            return result;
        } else {
            result.setCode(Constant.FAIL);
            result.setMsg("新增奖券失败！");
            return result;
        }
    }

    /**
     * 校验奖券
     *
     * @param lotteryTicket
     */
    public void checkTicket(LotteryTicketInfoVo lotteryTicket, String check) {
        if (check.equals("cashPackageType") && lotteryTicket.getCashPackageType() == null) {
            throw new RuntimeException("新增奖券失败:请选择现金红包类型!");
        }
        if (check.equals("VCT") && lotteryTicket.getCashPackageAmount() == null) {
            throw new RuntimeException("新增奖券失败:请输入虚拟现金红包金额!");
        }
        if (check.equals("BRT") && lotteryTicket.getInvestBackRate() == null) {
            throw new RuntimeException("新增奖券失败:请输入返现比例!");
        }
        if (check.equals("investBackRate")){
            int tasteType = lotteryTicket.getTasteType();
            if(tasteType == TasteType.INVEST_MULTIPLE.getValue() || tasteType == TasteType.INVEST_DAYS.getValue()){
                if(lotteryTicket.getInvestBackRate() == null || lotteryTicket.getInvestBackRate() <= 0.00) {
                    throw new RuntimeException("新增奖券失败:请填写正确的返现率!");
                }
            }
        }
        if (check.equals("cashPackageAmount")
                && (lotteryTicket.getCashPackageAmount() == null || lotteryTicket.getCashPackageAmount() <= 0.00)) {
            throw new RuntimeException("新增奖券失败:请填写优惠券的固定额度!");
        }
        if (check.equals("ticketAllAmount")
                && (lotteryTicket.getTicketAllAmount() == null || lotteryTicket.getTicketAllAmount() <= 0.00)) {
            throw new RuntimeException("新增奖券失败:请填写红包金额上限制!");
        }
        if (check.equals("startTime") && (lotteryTicket.getStartTime().getTime() <= new Date().getTime())) {
            throw new RuntimeException("新增奖券失败:开始小于当前时间！");
        }
        if (check.equals("validDayStartWithNow")
                && (lotteryTicket.getValidTermType() == 1 && lotteryTicket.getValidDayStart().getTime() < new Date()
                .getTime())) {
            throw new RuntimeException("新增奖券失败:开始有效小于当前时间！");
        }
        if (check.equals("validDayStartWithStartTime")
                && (lotteryTicket.getValidTermType() == 1 && lotteryTicket.getValidDayStart().getTime() < lotteryTicket
                .getStartTime().getTime())) {
            throw new RuntimeException("新增奖券失败:奖券的开始生效时间需大于奖池的开始时间!");
        }
        if (check.equals("validDayEndWithendTime")
                && (lotteryTicket.getValidTermType() == 1 && lotteryTicket.getValidDayEnd().getTime() < lotteryTicket
                .getEndTime().getTime())) {
            throw new RuntimeException("新增奖券失败:奖券的失效时间不得小于奖池的结束时间!");
        }
        if (check.equals("addInterestRate")
                && (lotteryTicket.getAddInterestRate() == null || lotteryTicket.getAddInterestRate() == 0)) {
            throw new RuntimeException("新增奖券失败:请填写加息率!");
        }
        if (check.equals("addInterestDays")
                && (lotteryTicket.getAddInterestDays() == null || lotteryTicket.getAddInterestDays() == 0)
                && AddInterestType.CUSTOM.getValue() == lotteryTicket.getAddInterestType()) {
            throw new RuntimeException("新增奖券失败:请填写加息时长!");
        }
        if (check.equals("publishPlatforms") && isBlank(lotteryTicket.getPublishPlatforms())) {
            throw new RuntimeException("新增奖券失败:请填勾选适用平台!");
        }
        if (check.equals("borrowTypes") && isBlank(lotteryTicket.getBorrowTypes())) {
            throw new RuntimeException("新增奖券失败:请填勾选适用标!");
        }
        if (check.equals("amount") && (lotteryTicket.getAmount() == null || lotteryTicket.getAmount() == 0)) {
            throw new RuntimeException("新增奖券失败:请填写奖券金额!");
        }
        if (check.equals("investMiniAmount")
                && (lotteryTicket.getInvestMiniAmount() == null || lotteryTicket.getInvestMiniAmount() == 0)) {
            throw new RuntimeException("新增奖券失败:请填写投资门槛金额!");
        }
        if (check.equals("title") && (lotteryTicketManager.checkLotteryTicketTitle(lotteryTicket.getTitle()) != 0)) {
            throw new RuntimeException("新增奖券失败:标题重复！");
        }
        if (check.equals("tasteType") && lotteryTicket.getTasteType() == null) {
            throw new RuntimeException("新增奖券失败:请选择体验金类型！");
        }
        if (check.equals("tasteTypeWithamount")
                && (lotteryTicket.getTasteType() == 0 && (lotteryTicket.getAmount() == null || lotteryTicket
                .getAmount() == 0))) {
            throw new RuntimeException("新增奖券失败:体验金类型按固定额度,请填写奖券金额!");
        }
        if (check.equals("tasteTypeWithmaxTasteAmount")
                && (lotteryTicket.getTasteType() == 1 && (lotteryTicket.getMaxTasteAmount() == null || lotteryTicket
                .getMaxTasteAmount() == 0))) {
            throw new RuntimeException("新增奖券失败:体验金类型按投资额度,请填写体验金上限制金额!");
        }
        if (check.equals("tasteRateDays")
                && (lotteryTicket.getTasteRateDays() == null || lotteryTicket.getTasteRateDays() == 0)) {
            throw new RuntimeException("新增奖券失败:请填写体验金的生息天数!");
        }
        if (check.equals("lotteryTicket") && (lotteryTicket == null)) {
            throw new RuntimeException("奖池不存在！");
        }
        if (check.equals("status") && (lotteryTicket.getStatus() == 0 || lotteryTicket.getStatus() == 2)) {
            throw new RuntimeException("奖池未生效或已失效！");
        }
        if (check.equals("freeTicketValue") && (lotteryTicket.getFreeTicketValue() == 0 || lotteryTicket.getFreeTicketValue()==null)) {
            throw new RuntimeException("新增奖券失败：减免利率必填！");
        }
        if (check.equals("repaymentTypes") && isBlank(lotteryTicket.getRepaymentTypes())) {
            throw new RuntimeException("新增奖券失败：请勾选适用还款类型！");
        }



        if (check.equals("borrowLoanPeriods") && !StringUtils.isBlank(lotteryTicket.getBorrowTypes())) {
            Long ids[] = NumberUtil.getTicketIds(lotteryTicket.getBorrowTypes());
            for (Long id : ids) {
                if (InvestType.PLANT_ATUO_INVEST.getValue() == id) {
                    if (StringUtils.isBlank(lotteryTicket.getBorrowLoanPeriods())) {
                        throw new RuntimeException("定期宝投资月份必填！");
                    }
                }
            }
        }
    }
    @Override
    public LotteryTicketInfoVo getLotteryTicketById(@RequestParam("id") Long id) {
        LotteryTicketInfoVo infoVo = lotteryTicketManager.getLotteryTicketById(id);
        if (infoVo.getAddInterestRate() != null) {
            infoVo.setAddInterestRate(NumberUtil.doubleDivide(infoVo.getAddInterestRate(), 0.01d, 2));
        }
        infoVo.setInteractiveTypeName(InteractiveType.getTextByValue(infoVo.getInteractiveType()).getText());
        infoVo.setGrantModeName(GrantModeType.getTextByValue(infoVo.getGrantMode()).getText());
        infoVo.setTypeName(LotteryTicketType.getTextByValue(infoVo.getType()).getText());
        if (infoVo.getType() == LotteryTicketType.CASH_PACKAGE.getValue()) {
            if (infoVo.getInvestBackRate() != null && infoVo.getInvestBackRate() != 0) {
                infoVo.setInvestBackRate(NumberUtil.doubleDivide(infoVo.getInvestBackRate(), 0.01d, 2));
            }
        }
        infoVo.setTasteName(null == infoVo.getTasteType() ? "" : TasteType.getTextByValue(infoVo.getTasteType())
                .getText());
        if(null !=infoVo.getFreeTicketType()){
            infoVo.setFreeTicketTypeName(FreeTicketType.getTextByValue(infoVo.getFreeTicketType()).getText());
        }
        infoVo.setId(id);
        return infoVo;
    }
    @Override
    public int updateLotteryTicket(@RequestBody LotteryTicketInfoVo lotteryTicket) {
        lotteryTicket.setStaffId(-1l);
//        if (lotteryTicket.getType() == LotteryTicketType.CASH_PACKAGE.getValue()) {
//            if (lotteryTicket.getInvestBackCurrentAmount() != null && lotteryTicket.getSubAmount() != null
//                    && lotteryTicket.getSubAmount() > 0
//                    && lotteryTicket.getInvestBackCurrentAmount() >= lotteryTicket.getSubAmount()) {
//                lotteryTicket.setInvestBackCurrentAmount(NumberUtil.doubleAddCheckNull(
//                        lotteryTicket.getInvestBackCurrentAmount(), -lotteryTicket.getSubAmount()));
//                TicketUseDetail detail = new TicketUseDetail();
//                detail.setTicketId(lotteryTicket.getId());
//                detail.setStatus(TicketUseStatus.SYS_SUB.getStatusValue());
//                detail.setAmount(lotteryTicket.getSubAmount());
//                detail.setStaffId(-1l);
//                List<TicketUseDetail> details = new ArrayList<TicketUseDetail>();
//                details.add(detail);
//                lotteryTicketManager.inserTicketUseDetails(details);
//            } else {
//                lotteryTicket.setInvestBackCurrentAmount(null);
//            }
//        }
        return lotteryTicketManager.updateLotteryTicket(lotteryTicket);
    }
    @Override
    public List<Map<String, Object>> queryTicketCombox() {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

        List<LotteryTicket> list = lotteryTicketManager.queryTicketCombox();

        if (!list.isEmpty()) {
            for (LotteryTicket ticket : list) {
                Map<String, Object> map = new HashMap<String, Object>();

                map.put("id", ticket.getId());
                map.put("title",
                        ticket.getId() + "|" + ticket.getTitle() + "|"
                                + LotteryTicketType.getTextByValue(ticket.getType()).getText());

                data.add(map);
            }
        }

        return data;
    }
}
